package com.wolfden.drugserver.banking;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.bukkit.plugin.Plugin;

import com.wolfden.drugserver.Constants;

public class MoneyMap {
	
	Plugin plugin;

	public MoneyMap(Plugin plugin) {
		this.plugin = plugin;
		try {
			Statement stat = Constants.connection.createStatement();
			stat.executeUpdate("create table if not exists accounts(name, balance);");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public long getBalance(String playerName) {

		try {
			Statement stat = Constants.connection.createStatement();
			ResultSet rs = stat
					.executeQuery("select balance from accounts where name='"
							+ playerName + "';");
			return rs.getLong("balance");
		} catch (Exception e) {
		}
		return -1;
	}

	public boolean canAfford(String playerName, long value) {

		if (getBalance(playerName) >= value)
			return true;

		return false;
	}

	public void withdraw(String playerName, long amount) {

		try {
			Statement stat = Constants.connection.createStatement();
			stat.executeUpdate("update accounts set balance=balance-" + amount
					+ " where name='" + playerName + "';");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void deposit(String playerName, long amount) {

		try {
			Statement stat = Constants.connection.createStatement();
			stat.executeUpdate("update accounts set balance=balance+" + amount
					+ " where name='" + playerName + "';");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void transfer(String from, String to, long amount) {

		withdraw(from, amount);
		deposit(to, amount);
	}

	public boolean accountExists(String playerName) {

		try {
			Statement stat = Constants.connection.createStatement();
			ResultSet rs = stat
					.executeQuery("select name from accounts where name='"
							+ playerName + "';");
			return rs.wasNull();
		} catch (Exception e) {
		}
		return false;
	}

	public void addAccount(String playerName, long startingBalance) {
			
			try {
				Statement stat = Constants.connection.createStatement();
				stat.executeUpdate("insert into accounts (name,balance) values ('" + playerName + "', "+startingBalance+");");
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
}